package com.czk.doc;

import com.czk.util.ClientUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;

/**
 * 过滤字段查询
 *
 * @Author:ChenZhangKun
 * @Date: 2021/6/14 17:27
 */
public class FilterFieldQuery {
    public static void main(String[] args) throws IOException {
        // 客户端
        RestHighLevelClient highLevelClient = ClientUtil.getHighLevelClient();
        // 查询客户端
        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        // 设置过滤字段
        String[] excludes = {};
        String[] includes = {"price", "title"};
        searchSourceBuilder.fetchSource(includes, excludes);
        searchRequest.indices("jd_goods").source(searchSourceBuilder);
        // 查询
        SearchResponse response = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
        highLevelClient.close();
    }
}
